package com.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil {
    //注册驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    //建立连接

    private static final String url = "jdbc:mysql://127.0.0.1:3306/test";
    private static final String user = "root";
    private static final String passWord = "7788";
    public static Connection getconnection(){

        try {
            return DriverManager.getConnection(url,user,passWord);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //增
    //删除
    //修改
    public static int upDataRow(String sql,Object[] value) throws SQLException {
        Connection connection = null;
        try{
            connection = getconnection();//建立连接
            PreparedStatement preparedStatement = connection.prepareStatement(sql);//预编译
            //设置占位符就是preparedStatement.setXXX("字段的列数","字段的名字")方法
            for (int i = 0;i< value.length;i++){
                if (value!=null){
                    preparedStatement.setObject(i+1,value[i]);
                }
            }
            int res = preparedStatement.executeUpdate();//接受受影响的行数
            return res;
        }finally {
            if (connection!= null){

                connection.close();
            }
        }
    }
    //查询
    public static List selRow(String sql,Object[] value,RowMapper rowMapper) throws SQLException {


        Connection connection = null;
        try{
            connection = getconnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //设置占位符号ps.setObject();
            List list = new ArrayList<>();
            for (int i = 0;i<value.length;i++){
                if (value!=null){
                    preparedStatement.setObject(i+1,value[i]);
                }
            }
            //返回查询的结果集合
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                //Integer empno = resultSet.getInt("empno")用接口实现
                Object resData = rowMapper.selRow(resultSet);
                list.add(resData);
            }
            return list;
        }finally {
            if (connection!=null){
                connection.close();
            }

        }

        //返回查询的结果

    }









}
